package com.blast.cn.persenter.check

import android.provider.Settings
import com.wxl.common.base.WorkPresenter
import com.wxl.common.util.DeviceUtil
import com.wxl.common.util.LocationUtils
import com.wxl.common.util.NetWorkUtils
import com.wxl.common.util.ObservableUtil
import com.wxl.common.wiget.TipPop
import io.reactivex.functions.Action
import kotlinx.android.synthetic.main.activity_check_device_layout.view.*

class CheckDeviceTimePresenter : WorkPresenter() {

    override fun onStartDoWork(vararg args: Any) {
        // 自动更新时间且网络可用，则保存时间
        rootView.checkProgressSub.text = "正在检查设备时间,请勿进行其他操作..."
        if (Settings.System.getInt(
                rootView.context.getContentResolver(),
                Settings.System.AUTO_TIME,
                0
            ) == 1 && NetWorkUtils.isNetWorkUse(rootView.context)
        ) {
            val time = System.currentTimeMillis()
            DeviceUtil.setDeviceTime(time)
        }

        ObservableUtil.delay(300, Runnable {
            checkDeviceTime()
        })
    }


    private fun checkDeviceTime(){
        rootView.checkProgressBar.progress = 25
        rootView.checkProgressText.text = "25%"
        val time = System.currentTimeMillis()
        if (time < DeviceUtil.getDeviceTime()) {
            val location = LocationUtils.getLocation(rootView.context)
            if(location != null) {
                DeviceUtil.setDeviceTime(location.time)
                doNext()
            } else {
                TipPop.showSure(rootView.context,"自检失败！\n错误代码007","重试", Action {
                    onStartDoWork()
                })
            }
        } else {
            DeviceUtil.setDeviceTime(time)
            doNext()
        }
    }
}